package router

import (
	"fmt"
	"net/http"
	"runtime/debug"

	"gitee.com/joseelin/goserve/res"
	"github.com/go-chi/chi"
)

// 错误拦截
func ErrorHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rvr := recover(); rvr != nil {

				data := fmt.Sprintf("%v", rvr)
				debug.PrintStack()
				res.Error(w, data)
			}
		}()
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

// 未找到
func NotFound(w http.ResponseWriter, r *http.Request) {
	res.NotFound(w)
}

// 不允许
func NotAllowed(w http.ResponseWriter, r *http.Request) {
	res.NotAllowed(w)
}

func New() chi.Router {
	r := chi.NewRouter()
	r.Use(ErrorHandler)
	r.NotFound(NotFound)
	r.MethodNotAllowed(NotAllowed)
	return r
}
